package com.function.utils;

import com.alibaba.fastjson.JSONObject;
import com.function.domin.vo.AddressVO;
import com.function.properties.BaiduMapProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import static com.alibaba.fastjson.util.IOUtils.readAll;

@Slf4j
@Component
public class BaiduMapUtils {

    @Autowired
    private BaiduMapProperties baiduMapProperties;

    /**
     * 获取公网ip地址
     */
    public String getPublicIp() throws IOException {
        URL url = new URL("http://checkip.amazonaws.com");
        //打开一个输入流，允许从指定的URL读取数据
        //BufferedReader提供了一个缓冲区, 加快数据读取速度
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        //readLine方法用来读取一行字符串，trim方法用来除去字符串两端的空白字符
        String publicIp = br.readLine().trim();
        br.close();
        return publicIp;
    }

    /**
     * 获取当前地址
     * @param ip
     * @return
     * @throws IOException
     */
    public JSONObject getAddress(String ip) throws IOException {
        String ak = baiduMapProperties.getAk();
        String url = baiduMapProperties.getAddressUrl() + "ip=" + ip + "&ak=" + ak;

        //从百度地图的ip定位api获取json格式的返回数据
        InputStream is = new URL(url).openStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject addressJson = JSONObject.parseObject(jsonText);
        is.close();

       return addressJson;
    }

    /**
     * 获取当前天气
     * @param districtId
     * @return
     * @throws IOException
     */
    public JSONObject getWeather(String districtId) throws IOException {
        String ak = baiduMapProperties.getAk();
        String url = baiduMapProperties.getWeatherUrl() + "district_id=" + districtId + "&data_type=all" + "&ak=" + ak;

        //从百度地图的国内天气查询api获取json格式的返回数据
        InputStream is = new URL(url).openStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject weatherJson = JSONObject.parseObject(jsonText);
        is.close();

        return weatherJson;
    }

}
